<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { Toast } from "tdesign-mobile-vue";
import ImgList from "./common/imgList.vue";
import {queryGraphCategory, queryTemplateCategory, queryTemplateList} from "@/api/editor/materials";
import { useEditor } from "@/views/Editor/app";

// 取得编辑器和全局分页信息
const { editor } = useEditor();
// 定义响应式数据
const pages = ref<Record<string, any>>({});
const visibleSticker = ref(false);
const keyword = ref('');
const currentCate = ref(null);
const cateList = ref([]);
const $dialog: any = inject('$dialog');
// 事件发射器
const emit = defineEmits(['success']);
const currentTab = ref(0);
// 添加贴纸
const add = async (url) => {
    emit('success', url);
};

// 打开和关闭贴纸选择器
const open = () => { visibleSticker.value = true; };
const hide = () => { visibleSticker.value = false; };

// 获取分类数据
const fetchData = async () => {
    try {
        const res = await queryTemplateCategory();
        if (res.success) {
            cateList.value = res.data;
            cateList.value.forEach(cate => {
                if (!pages.value[cate.id]) {
                    pages.value[cate.id] = {
                        noMore: false,
                        dataList: [],
                        params: {
                            pageNum: 1,
                            pageSize: 30,
                            query:{templateCategoryId: cate.id,}
                        },
                    };
                }
            });
            selectCate(0);
        }
    } catch (error) {
        console.error('获取分类失败', error);
    }
};

// 选择分类并加载数据
const selectCate = (index) => {
    currentCate.value = cateList.value[index];
    loadList(currentCate.value.id);
};

// 加载贴纸数据
const loadList = async (categoryId) => {
    const page = pages.value[categoryId];
    if (page.noMore) return; // 如果没有更多数据，直接返回

    try {
        const res = await queryTemplateList(page.params);
        if (res.success) {
            const newDataList = res.data.list;
            page.dataList.push(...newDataList);
            page.params.pageNum += 1;
            page.noMore = page.dataList.length >= res.data.total;

            // 更新 pages 以触发响应性
            pages.value = { ...pages.value };
        }
    } catch (error) {
        console.error('加载贴纸失败', error);
    }
};
const onTabTemplate = (template:any) => {
    $dialog.confirm({
        title: '确认使用此模板？',
        content: '此模板将替换已存在的模板数据',
        confirmBtn: '确认',
        cancelBtn: '取消',
        zIndex:11601,
        overlayProps:{
            zIndex:11600,
        },
        onConfirm: () => {
            if (template.jsonContent) {
                try {
                    editor.importJsonToCurrentPage(JSON.parse(template.jsonContent), true)
                }catch (e) {
                    editor.importJsonToCurrentPage(template.jsonContent, true)
                }
            }
            hide()
        }
    });
}
// 组件挂载时获取数据
onMounted(() => {
    fetchData();
});

// 暴露给外部调用的方法
defineExpose({
    add, open, hide,
});
</script>

<template>
    <t-popup v-model="visibleSticker" placement="bottom" destroy-on-close :showOverlay="false">
        <div>
            <div class="pop-header">
                <div class="title p-l-0! overflow-auto">
                    <t-tabs v-model="currentTab" :spaceEvenly="false" @change="selectCate">
                        <t-tab-panel
                                v-for="(item, index) in cateList"
                                :key="item.id"
                                :value="index"
                                :label="item.categoryName"
                        />
                    </t-tabs>
                </div>
                <div class="btn btn--cancel" @click="hide">
                    <t-icon name="close-circle" size="18"></t-icon>
                </div>
            </div>

            <div class="pop-content">
                <img-list
                        v-for="(item, index) in cateList"
                        :key="'im_'+index"
                        v-show="currentCate.id === item.id"
                        :data="pages[item.id]?.dataList || []"
                        :no-more="pages[item.id]?.noMore || false"
                        @fetchData="loadList(item.id)"
                        @add="add"
                        height="calc(100vh - 200px)"
                >
                    <template #default="{ list }">
                        <div class="groups">
                            <div data-v-ef675ca6="" class="box" v-for="(item,index) in list" :key="index">
                                <div data-v-ef675ca6="" class="group">
                                    <img data-v-ef675ca6=""
                                         :src="item.cover"
                                         :alt="item.name">
                                    <div data-v-ef675ca6="" class="like"></div>
                                </div>
                                <div data-v-ef675ca6="" class="title">{{item.title}}</div>
                                <div data-v-ef675ca6="" class="user">
                                    <div data-v-ef675ca6="" class="left">
                                        <!-- <span data-v-ef675ca6="" class="tag">VIP</span> -->
                                    </div>
                                    <div data-v-ef675ca6="" class="button">
                                        <t-button size="extra-small" theme="primary" @click="onTabTemplate(item)">使用</t-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                </img-list>

            </div>
        </div>
    </t-popup>
</template>

<style lang="less" scoped>
@import "../../../styles/pop-style.less";

.groups {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  overflow-y: auto;
  padding: .625rem .3125rem;
  -webkit-overflow-scrolling: touch
}

.groups .box {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-align: start;
  -webkit-align-items: flex-start;
  -ms-flex-align: start;
  align-items: flex-start;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
  border: .0625rem solid #f4f4f4;
  overflow: hidden;
  width: 46%;
  margin: 0 2% .625rem
}

.groups .box .group {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  background-color: #f4f4f4;
  width: 100%;
  height: calc(420px * .42);
  border-radius: .1875rem
}

.groups .box .group img {
  max-height: 90%;
  max-width: 90%
}

.groups .box .title {
  display: block;
  overflow: hidden;
  padding: 0 .5rem;
  margin-top: .75rem;
  width: 100%;
  -o-text-overflow: ellipsis;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: .75rem;
  color: #241e24
}

.groups .box .user {
  display: -webkit-inline-box;
  display: -webkit-inline-flex;
  display: -ms-inline-flexbox;
  display: inline-flex;
  -webkit-box-pack: justify;
  -webkit-justify-content: space-between;
  -ms-flex-pack: justify;
  justify-content: space-between;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  overflow: hidden;
  width: 100%;
  padding: .625rem .5rem
}

.groups .box .user .left {
  display: -webkit-inline-box;
  display: -webkit-inline-flex;
  display: -ms-inline-flexbox;
  display: inline-flex;
  width: 70%;
  -webkit-box-flex: 0;
  -webkit-flex-grow: 0;
  -ms-flex-positive: 0;
  flex-grow: 0;

  .tag {
    background-color: #0009;
    box-shadow: 0 1px 4px #00000029;
    padding: 0 6px;
    color: #FFD700;
    border-radius: 4px;
  }
}
</style>
